package com.xiaoyu.client.ui.fragment.main;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.xiaoyu.client.ClientConstants;
import com.xiaoyu.client.R;
import com.xiaoyu.client.adapter.mall.MallGoodsAdapter;
import com.xiaoyu.client.adapter.mall.MallRecomAdapter;
import com.xiaoyu.client.adapter.mall.MallTypeAdapter;
import com.xiaoyu.client.model.goods.GoodsBean;
import com.xiaoyu.client.model.goods.GoodsParam;
import com.xiaoyu.client.model.goods.MallHomeBean;
import com.xiaoyu.client.model.goods.MallHomeBean.DataBean.*;
import com.xiaoyu.client.network.NetworkConstants;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.loader.banner.BannerImageLoader;
import com.xiaoyu.client.ui.activity.mall.GoodsDetailsActivity;
import com.xiaoyu.client.ui.activity.mall.GoodsMoreTagActivity;
import com.xiaoyu.client.ui.activity.mall.GoodsSearchActivity;
import com.xiaoyu.client.ui.activity.mall.GoodsTagActivity;
import com.xiaoyu.client.ui.activity.mall.PartsLimitActivity;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.OnItemRecyClickListener;
import com.xiaoyu.commonlib.ui.SpacesItemDecoration;
import com.xiaoyu.commonlib.ui.widget.NestedGridView;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.xiaoyu.commonlib.utils.UIUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 商城
 * Created by jk on 2018/9/28.
 */
public class MallFragment extends Fragment implements View.OnClickListener {
    @BindView(R.id.fragment_mall_top_banner)
    Banner mTopBanner;//顶部轮播图
    @BindView(R.id.fragment_mall_search_layout)
    EditText mSearchBtn;//搜索布局
    @BindView(R.id.fragment_mall_type_list_container)
    NestedGridView mTypeContainer;//类型列表
    @BindView(R.id.fragment_mall_middle_banner)
    Banner mMidBanner;//中部轮播图
    @BindView(R.id.fragment_mall_peijian_layout)
    LinearLayout peiLayout;//配件容器
    @BindView(R.id.fragment_mall_peijian_one_img)
    ImageView peiOneImg;//配件1图片
    @BindView(R.id.fragment_mall_peijian_two_img)
    ImageView peiTwoImg;//配件2图片
    @BindView(R.id.fragment_mall_recom_list_container)
    RecyclerView mRecomContainer;//推荐列表
    @BindView(R.id.fragment_mall_more_list_container)
    NestedGridView mMoreContainer;//更多产品
    @BindView(R.id.fragment_mall_refresh_layout)
    SmartRefreshLayout mRefreshLayout;//刷新控件
    private View mView;

    public static final String GOODS_UPDATE_OR_LIMIT = "goods_update_limit";
    private MallTypeAdapter mTagAdapter;//类型适配器
    private MallRecomAdapter mRecomAdapter;//新品推荐适配器
    private MallGoodsAdapter mGoodsAdapter;//更多产品适配器

    private List<LunboBean> mTopBannerList = new ArrayList<>();//顶部轮播图数据列表
    private List<RelunboBean> mMidBannerList = new ArrayList<>();//中部轮播图数据列表
    private List<String> mTopList = new ArrayList<>();//顶部轮播图图片数据列表
    private List<String> mMidList = new ArrayList<>();//顶部轮播图图片数据列表
    private List<PeixianBean> mPeiList = new ArrayList<>();//配件列表
    private List<MallTagBean> mTagList = new ArrayList<>();
    private List<RelistBean> mRecomList = new ArrayList<>();
    private List<GoodsParam> mGoodsList = new ArrayList<>();

    private int page = 1;
    private int totalPage;//总页数

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.fragment_mall, container, false);
            ButterKnife.bind(this, mView);
            initView();
        }
        ViewGroup parent = (ViewGroup) mView.getParent();
        if (parent != null) {
            parent.removeView(mView);
        }
        return mView;
    }

    @Override
    public void onResume() {
        super.onResume();
        page = 1;
        mTopBannerList.clear();
        mMidBannerList.clear();
        mTopList.clear();
        mMidList.clear();
        mTagList.clear();
        mRecomList.clear();
        mGoodsList.clear();
        getRecomBanner();
        getMoreProduct();
    }

    //搜索布局点击监听
    @OnClick(R.id.fragment_mall_search_layout)
    public void searchClick() {
        startActivity(new Intent(getActivity(), GoodsSearchActivity.class));
    }


    private void initView() {
        //顶部轮播图
        mTopBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        mTopBanner.setIndicatorGravity(BannerConfig.CENTER);
        //设置是否自动轮播（不设置则默认自动）
        mTopBanner.isAutoPlay(true);
        //设置是否允许手动滑动轮播图
        mTopBanner.setViewPagerIsScroll(true);
        //设置轮播图片间隔时间（不设置默认为2000）
        mTopBanner.setDelayTime(2000);
        mTopBanner.setImageLoader(new BannerImageLoader());
        mTopBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent(getActivity(), GoodsDetailsActivity.class);
                intent.putExtra(ClientConstants.GOODS_ID, mGoodsList.get(position).getGoodsid());
                startActivity(intent);
            }
        });

        mTopBanner.setFocusable(true);
        mTopBanner.setFocusableInTouchMode(true);
        mTopBanner.requestFocus();


        //中部轮播图
        mMidBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        mMidBanner.setIndicatorGravity(BannerConfig.CENTER);
        //设置是否自动轮播（不设置则默认自动）
        mMidBanner.isAutoPlay(true);
        //设置是否允许手动滑动轮播图
        mMidBanner.setViewPagerIsScroll(true);
        //设置轮播图片间隔时间（不设置默认为2000）
        mMidBanner.setDelayTime(2000);
        mMidBanner.setImageLoader(new BannerImageLoader());
        mMidBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent(getActivity(), GoodsDetailsActivity.class);
                intent.putExtra(ClientConstants.GOODS_ID, mGoodsList.get(position).getGoodsid());
                startActivity(intent);
            }
        });

        //类型列表
        mTagAdapter = new MallTypeAdapter(getActivity(), mTagList);
        mTypeContainer.setAdapter(mTagAdapter);
        mTypeContainer.setOnItemClickListener(onTagClickListener);

        //新品推荐列表
        mRecomAdapter = new MallRecomAdapter(getActivity(), mRecomList);
        GridLayoutManager recomManager = new GridLayoutManager(getActivity(), 3);
        recomManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {

            @Override
            public int getSpanSize(int position) {
                return (position == 0) ? 3 : 1;
            }
        });
        mRecomContainer.setLayoutManager(recomManager);
        mRecomContainer.addItemDecoration(new SpacesItemDecoration(UIUtils.dip2px(10), 3));
        mRecomContainer.setAdapter(mRecomAdapter);
        mRecomAdapter.setOnItemRecyClickListener(onItemRecyClickListener);

        //配件升级、限时购买
        for (int i = 0; i < peiLayout.getChildCount(); i++) {
            peiLayout.getChildAt(i).setOnClickListener(this);
        }

        //更多产品
        mGoodsAdapter = new MallGoodsAdapter(getActivity(), mGoodsList);
        mMoreContainer.setAdapter(mGoodsAdapter);
        mMoreContainer.setOnItemClickListener(onGoodsItemClickListener);

        //刷新控件
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsHeader(context);
            }
        });
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
        mRefreshLayout.setOnLoadMoreListener(loadMoreListener);
        mRefreshLayout.setNoMoreData(false);
        mRefreshLayout.setEnableRefresh(false);
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        if (v == peiLayout.getChildAt(0)) {//配件升级
            intent = new Intent(getActivity(), PartsLimitActivity.class);
            intent.putExtra(GOODS_UPDATE_OR_LIMIT, 0);
            startActivity(intent);
        } else if (v == peiLayout.getChildAt(1)) {//限时购买
            intent = new Intent(getActivity(), PartsLimitActivity.class);
            intent.putExtra(GOODS_UPDATE_OR_LIMIT, 1);
            startActivity(intent);
        }
    }

    /**
     * 类型item点击监听
     */
    private AdapterView.OnItemClickListener onTagClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent;
            if (position != parent.getAdapter().getCount() - 1) {
                String tagId = mTagList.get(position).getGoodstagid();
                String tagName = mTagList.get(position).getGoodstagname();
                intent = new Intent(getActivity(), GoodsTagActivity.class);
                intent.putExtra(ClientConstants.GOODS_TAG_ID, tagId);
                intent.putExtra(ClientConstants.GOODS_TAG_NAME, tagName);
                startActivity(intent);
            } else {
                intent = new Intent(getActivity(), GoodsMoreTagActivity.class);
                startActivity(intent);
            }
        }
    };


    /**
     * 新品推荐item点击监听
     */
    private OnItemRecyClickListener onItemRecyClickListener = new OnItemRecyClickListener() {
        @Override
        public void onItemRecyClick(View view, int position) {
            Intent intent = new Intent(getActivity(), GoodsDetailsActivity.class);
            intent.putExtra(ClientConstants.GOODS_ID, mRecomList.get(position).getGoodsid());
            startActivity(intent);
        }
    };

    /**
     * 更多产品item点击监听
     */
    private AdapterView.OnItemClickListener onGoodsItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(getActivity(), GoodsDetailsActivity.class);
            intent.putExtra(ClientConstants.GOODS_ID, mGoodsList.get(position).getGoodsid());
            startActivity(intent);
        }
    };

    /**
     * 更多产品列表的加载更多
     */
    private OnLoadMoreListener loadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            if (page < totalPage) {
                page = page + 1;
                getMoreProduct();
                mRefreshLayout.setNoMoreData(false);
                mRefreshLayout.finishLoadMore();
            } else {
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(true);
                mRefreshLayout.finishLoadMoreWithNoMoreData();
                ToastUtil.showBelowToast(getActivity(), "没有更多数据！");
            }
        }
    };

    /**
     * 获取轮播图、推荐、类型、配件升级
     */
    private void getRecomBanner() {
        NetworkManager.getMallRecom(new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                ParseMallRecomInfo(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
            }
        });
    }

    private void ParseMallRecomInfo(String result) {
        ToastUtil.logResult("商城首页类别", result);
        MallHomeBean bean = new Gson().fromJson(result, MallHomeBean.class);

        //轮播图
        mMidBannerList.clear();
        mTopBannerList.clear();
        mTopList.clear();
        mMidList.clear();
        mTopBannerList.addAll(bean.getData().getLunbo());
        mMidBannerList.addAll(bean.getData().getRelunbo());
        for (int i = 0; i < mTopBannerList.size(); i++) {
            mTopList.add(i, mTopBannerList.get(i).getLunboimg());
        }
        for (int i = 0; i < mMidBannerList.size(); i++) {
            mMidList.add(i, mMidBannerList.get(i).getGoodslbimg());
        }
        mTopBanner.setImages(mTopList);
        mMidBanner.setImages(mMidList);
        mTopBanner.start();
        mMidBanner.start();

        //类型
        mTagList.clear();
        mTagList.addAll(bean.getData().getTag());
        mTagAdapter.updateList(mTagList);

        //新品推荐
        mRecomList.clear();
        mRecomList.addAll(bean.getData().getRelist());
        mRecomAdapter.updateList(mRecomList);

        //配件
        mPeiList.clear();
        mPeiList.addAll(bean.getData().getPeixian());
        if (mPeiList.size() == 1) {
            Glide.with(this).load(mPeiList.get(0).getImgurl()).into(peiOneImg);
        }
        if (mPeiList.size() == 2) {
            Glide.with(this).load(mPeiList.get(0).getImgurl()).into(peiOneImg);
            Glide.with(this).load(mPeiList.get(1).getImgurl()).into(peiTwoImg);
        }


    }

    /**
     * 获取更多产品信息
     */
    private void getMoreProduct() {
        NetworkManager.getMallMoreProduct(page, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                parseMoreInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {

            }
        });
    }

    private void parseMoreInfoSuc(String result) {
        if (page == 1) {
            mGoodsList.clear();
        }
        GoodsBean bean = new Gson().fromJson(result, GoodsBean.class);
        mGoodsList.addAll(bean.getData().getList());
        totalPage = Integer.parseInt(bean.getData().getCount());
        mGoodsAdapter.updateList(mGoodsList);
    }


    //如果你需要考虑更好的体验，可以这么操作
    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        mTopBanner.startAutoPlay();
        mMidBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        mTopBanner.stopAutoPlay();
        mMidBanner.stopAutoPlay();
    }

}
